# (c) 2010 Michael Penhallegon
# All Rights Reserved

import gdata.geo
import gdata.media
import gdata.photos.service

import sys, os, pickle, pathloader

from datetime import datetime, timedelta
from socket import gaierror

class Photos():
    '''Photos class is used as development-ready class
    to retrieve photos from picasa if that does not work
    then it will create a local-sourced url list to pull 
    from. The constructor requires a username and password'''

    def __init__(self, password, username, update=3600):
        self.path = pathloader.paths["apppath"]+'cache.pkl'
        # check the modification of our cache to make sure
        # it has been update in a day

        # use os.pathgetmtime to get a timestamp convert to datetime
        # then substract from current time to get a timedelta
        # if more than 1/4 a day then pull the information from there
        if datetime.now() - datetime.fromtimestamp(os.path.getmtime(self.path)) > timedelta(0,update,0):
            self.createurls(password,username)
        else:
            self.urls = pickle.load(open(self.path,"r"))

    def createurls(self,password, username):
        try:
            # logins into picasa
            gd_client = gdata.photos.service.PhotosService()
            gd_client.email = username
            gd_client.password = password
            gd_client.source = 'crimsonfae'
            gd_client.ProgrammaticLogin()

            # queries the feed for the last 25 photos
            # then, filter list to only show photos that are public
            self.photos = gd_client.GetUserFeed(kind='photo',limit='25')
            isPublic = lambda entry: entry.extension_elements[0].text == 'public' 
            publicPhotos = filter(isPublic,self.photos.entry)

            # extract the thumbnail and picasa url and limits
            # results to the first 18
            exthumbs = lambda g:g.media.thumbnail[0].url
            exUrl = lambda g:g.GetHtmlLink().href
            thumbpath = map(exthumbs, publicPhotos)
            fullpath = map(exUrl, publicPhotos)
            self.urls = zip(thumbpath[:18],fullpath[:18])
            pickle.dump(self.urls,open(self.path,'w'))

        except gaierror:
            # capture any exception to load local files
            # with local files use same data structure
            
            #print exceptions
            print sys.exc_type

            #create a directory string this assumes all
            # the locally stored files are the same name
            # and number in series
            dirpath = 'http://localhost:8000/static/Columbia'
            createthumbpath = lambda n:str(
                "%s%d.jpg?height=64" % (dirpath,n,))
            createpath = lambda n:str(
                "%s%d.jpg" % (dirpath,n,))
            thumbpath = map(createthumbpath,range(1,6))
            fullpath = map(createpath, range(1,6))
            self.urls = zip(thumbpath, fullpath)
            
    def geturls(self):
        '''retrieves the list of urls, is made up of entries
        with a tuple first with the thumbnail url then the full-size url
        when called'''
        return self.urls
